package pgsql

import (
	"a-common/config"
	"a-system/domain/entity"
	"errors"
	"log/slog"
	"sync"
	"time"

	_ "github.com/lib/pq"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
	"xorm.io/xorm/names"
)

var (
	pgsqlOnce       sync.Once
	pgsqlClientTemp *pgsqlClient
)

type pgsqlClient struct {
	PgCli *xorm.Engine
}

func NewPgsqlCli() *pgsqlClient {
	pgsqlOnce.Do(func() {
		pgsqlClientTemp = &pgsqlClient{
			PgCli: pg(),
		}
	})
	return pgsqlClientTemp
}

func pg() *xorm.Engine {
	conf := config.Config.Database
	// engine, err := xorm.NewEngine("postgres", "postgresql://Administrator:postgres@127.0.0.1:5432/aijuan?sslmode=disable&TimeZone=Asia/Shanghai")
	engine, err := xorm.NewEngine("postgres", conf.Pgsql.Dns)
	if err != nil {
		panic(errors.New("pgSQL initialization failed, " + err.Error()))
	}
	// 设置是否打印日志
	engine.ShowSQL(conf.ShowSQL)
	engine.Logger().SetLevel(log.LOG_DEBUG)
	// 设置数据库连接池参数
	engine.SetMaxOpenConns(conf.MaxOpenConn)
	engine.SetMaxIdleConns(conf.MaxIdleConn)
	// 最长链接时间 1.16版本以后才有的
	engine.SetConnMaxLifetime(10 * time.Minute)
	// 支持struct为驼峰式命名
	engine.SetMapper(names.GonicMapper{})
	// 创建表
	err = createTables(engine)
	if err != nil {
		slog.Error("初始化数据表错误:" + err.Error())
	}
	return engine
}

func createTables(engine *xorm.Engine) error {
	tables := []any{
		new(entity.SysUser),
		new(entity.SysMenu),
	}
	// 批量创建表
	for _, table := range tables {
		has, err := engine.IsTableExist(table)
		if err != nil {
			return err
		}
		if !has {
			err := engine.Sync2(table)
			if err != nil {
				return err
			}
		}
	}
	return nil
}
